package com.aleven.lease.web.admin.service.impl;

import com.aleven.lease.common.constant.RedisConstant;
import com.aleven.lease.common.exception.LeaseException;
import com.aleven.lease.common.result.ResultCodeEnum;
import com.aleven.lease.common.utils.JwtUtil;
import com.aleven.lease.model.entity.SystemUser;
import com.aleven.lease.model.enums.BaseStatus;
import com.aleven.lease.web.admin.mapper.SystemUserMapper;
import com.aleven.lease.web.admin.service.LoginService;
import com.aleven.lease.web.admin.vo.login.CaptchaVo;
import com.aleven.lease.web.admin.vo.login.LoginVo;
import com.aleven.lease.web.admin.vo.system.user.SystemUserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wf.captcha.SpecCaptcha;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private SystemUserMapper systemUserMapper;
    @Override
    public CaptchaVo getCaptcha() {
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 4);// 宽，高，位数
        String code = specCaptcha.text().toLowerCase();//将验证码转为小写存入redis,后期把用户输入的验证码也转成小写来校验，实现不区分大小写
        String key = RedisConstant.ADMIN_LOGIN_PREFIX+ UUID.randomUUID();//对验证码生成一个唯一id
        String img = specCaptcha.toBase64();
        // 存入redis并设置过期时间为60秒
        redisTemplate.opsForValue().set(key,code,RedisConstant.APP_LOGIN_CODE_RESEND_TIME_SEC, TimeUnit.SECONDS);
        // 将key和img返回给前端
        return new CaptchaVo(img, key);
    }

    @Override
    public String login(LoginVo loginVo) {
        //1.判断有没有输入验证码
        if (StringUtils.isEmpty(loginVo.getCaptchaCode())){
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_NOT_FOUND);
        }
        //2.判断验证码是否正确且未过期
        String code = redisTemplate.opsForValue().get(loginVo.getCaptchaKey());//判断id判断redis中是否存在该验证码
        //过期
        if (code==null){
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_EXPIRED);
        }
        //验证码错误
        if(!code.equals(loginVo.getCaptchaCode())){
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR);
        }
        //3.校验用户是否存在
        SystemUser user = systemUserMapper.selectOne(new LambdaQueryWrapper<SystemUser>()
                .eq(SystemUser::getUsername, loginVo.getUsername()));
        if (user==null){
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_NOT_EXIST_ERROR);
        }
        //4.校验用户状态
        if (user.getStatus()== BaseStatus.DISABLE) {
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR);
        }
        //5.校验密码
        //把用户密码加密然后和数据库校验
        if (!user.getPassword().equals(DigestUtils.md5Hex(loginVo.getPassword()))){
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
        }
        //6.生成token并返回
        String token = JwtUtil.createToken(user.getId(), user.getUsername());

        return token;
    }

    @Override
    public SystemUserInfoVo getLoginUserInfo(Long userId) {
        SystemUser systemUser = systemUserMapper.selectById(userId);
        SystemUserInfoVo userInfoVo = new SystemUserInfoVo();
        userInfoVo.setName(systemUser.getName());
        userInfoVo.setAvatarUrl(systemUser.getAvatarUrl());
        return userInfoVo;
    }
}
